<template>
  <div class="toastWrapper" :class="toastPosition">
    <div class="toast">
      <div class="message">
        <slot v-if="!enableHtml"></slot>
        <div v-else v-html="$slots.default[0]"></div>
      </div>
      <div class="line" />
      <div class="closeBtn" @click="onClose">{{ closeButton.text }}</div>
    </div>
  </div>
</template>
<script>
// 构造组件的选项
export default {
  name: 'zToast',
  props: {
    autoClose: {
      type: [Number, Boolean],
      default: 5,
      validator (value) {
        return value === false || typeof value === 'number'
      }
    },
    position: {
      type: String,
      default: 'top',
      validator (value) {
        return ['top', 'middle', 'bottom'].includes(value)
      }
    },
    enableHtml: {
      type: Boolean,
      default: false
    },
    closeButton: {
      type: Object,
      default () {
        return {
          text: '关闭', callback: undefined
        }
      }
    }
  },
  mounted () {
    this.execAutoClose()
  },
  computed: {
    toastPosition () {
      return [`position-${this.position}`]
    }
  },
  methods: {
    close () {
      this.$el.remove()
      this.$emit('close')
      this.$destroy()
    },
    execAutoClose () {
      if (this.autoClose) {
        setTimeout(() => {
          this.close()
        }, this.autoClose * 1000)
      }
    },
    onClose () {
      this.close()
      if (this.closeButton.callback && typeof this.closeButton.callback === 'function') {
        this.closeButton.callback(this)
      }
    }
  }
}
</script>
<style scoped lang="scss">
$animation-duration: 300ms;
.toastWrapper {
  position: fixed;
  height: 40px;
  background: rgba(0,0,0,0.74);
  box-shadow: 0px 0px 3px 0px rgba(0,0,0,0.50);
  left: 50%;
  color: #ffffff;
  border-radius: 5px;
  padding-left: 16px;
  padding-right: 16px;
  transform: translateX(-50%);
  &.position-top {
    top: 10%
  }
  &.position-middle {
    top: 50%
  }
  &.position-bottom {
    bottom: 0
  }
  > .toast {
    display: flex;
    height: 100%;
    justify-content: space-between;
    align-items: center;
    > .message {
      margin-right: 10px;
    }
    > .line {
      width: 1px;
      height: 100%;
      background-color: #ffffff;
    }
    > .closeBtn {
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
</style>
